<?php
include("pq.class.php");
include("myzhuaqu.php");

function clcss($nr,$url){
    $nr=linecss($nr);
    $nr=dquanurl($nr,$url);
    return $nr;
}

function linecss($nr){
    while(preg_match("/(\n[^\{\}\r\n]*\, *)[\r\n]+?(?!\s)/Uix",$nr)){
        $nr=preg_replace("/(\n[^\{\}\r\n]*\, *)[\r\n]+?(?!\s)/Uix","\\1",$nr);
    }
    $nr=preg_replace("/\}/Uisx","}\r\n",$nr);
    $nr=preg_replace_callback("/\{(.*)\}/Uisx","delrn",$nr);
    $nr=preg_replace("/ +/"," ",$nr);
    $nr=preg_replace("/^[^\{\}]*$/m","",$nr);
    $nr=preg_replace("/((\n|\r)+\s*(\r|\n)+)+/s","\r\n",$nr);
    $nr=preg_replace("/\/\*[^\r\n]*\*\//s","",$nr);
    return $nr;
}

function delrn($em){
    $em[1]=preg_replace("/(\r|\n)+/","",$em[1]);
    $em[1]=preg_replace("/\s+/"," ",$em[1]);
    return "{".$em[1]."}";
}

function xpath($str){
    $str=trim($str);
    return $str;
}

if(!function_exists('chec')) {
    function chec($em)
    {
        if ($em[1] != "hover" && $em[1] != "last" && $em[1] != "focus" && $em[1] != "active" && $em[1] != "after" && $em[1] != "current") {
            return "[^<>]*" . $em[1];
        }
        return "";
    }
}

if(!function_exists('findCss')) {
    function findCss($o, $oxpath = "")
    {
        static $firstdo = 0;
        global $has, $cssStr, $pq;
        $re = $o->tagName();
        $re = addsla($re);

        //全局的，仅执行一次
        if (!$firstdo) {
            preg_match_all("/^(\*|html|body|a|a:link|a:hover|ins)\s*\{.*\}/imx", $cssStr, $nn);
            for ($i = 0; $i < count($nn[0]); $i++) {
                if (!in_array($nn[0][$i], $has)) {
                    $firstdo++;
                    $has[] = $nn[0][$i];
                }
            }
        }

        $xpath = $o->getXpath();

        //处理上层引用
        $xpathRe = xpathRe($xpath);
        preg_match_all("/^{$xpathRe}\s*\{.*\}/imx", $cssStr, $nn);
        $c = count($nn[0]);
        for ($i = 0; $i < $c; $i++) {
            if ($nn[0][$i] != null && !in_array($nn[0][$i], $has)) {
                $has[] = $nn[0][$i];
            }
        }

        $arr = $o->children()->elements;
        $oxpath = (empty($oxpath)) ? array() : $oxpath;
        for ($i = 0; $i < count($arr); $i++) {
            $xpath = pq($arr[$i])->getInnerXpath();
            if (is_array($oxpath) && !in_array($xpath, $oxpath)) {
                $oxpath[] = $xpath;
                findCss(pq($arr[$i]));
            }

        }
        return $has;
    }


    function xpathRe($arr)
    {
        $result = "";
        for ($i = 0; $i < count($arr); $i++) {
            $s = "";
            if ($arr[$i]['id'] != null) {
                $s .= "\#" . $arr[$i]['id'];
            }
            if ($arr[$i]['tagName'] != null) {
                $s .= "|\s*" . $arr[$i]['tagName'];
            }
            if ($arr[$i]['class'] != null) {
                $xx = explode(" ", $arr[$i]['class']);
                $tm = "";
                for ($j = 0; $j < count($xx); $j++) {
                    if (trim($xx[$j]) != "") $tm .= "|\s*\." . trim($xx[$j]);
                }
                $s .= "|(?:" . preg_replace("/^\|/", "", $tm) . ")?";
            }
            $s = "(?:" . preg_replace("/^\|/", "", $s) . ")*[\s\>]*";
            $result .= $s;
        }
        return $result;
    }


    function findCss2($re, $minnr)
    {
        global $has, $CSS, $alreadytest;
        $re = addsla($re);
        $return = "";
        for ($i = 0; $i < count($CSS); $i++) {
            if (preg_match("/(^|\s){$re}(\b|$|\s|\:)/Usx", $CSS[$i]->xp)) { //preg_match("/body/Uisx",$re)&&preg_match("/body/Uisx",$CSS[$i]->xp)
                $aa = explode(",", $CSS[$i]->xp);
                for ($j = 0; $j < count($aa); $j++) {
                    $temp = $aa[$j];
                    if (preg_match("/>/", $temp)) continue;
                    $temp = str_replace("*", "\*", $temp);
                    $temp = str_replace(" ", ".*", $temp);
                    $temp = preg_replace("/\.([a-zA-Z0-9_\-]+)/isx", "[^<>]*\bclass=[\"']([a-bA-Z0-9]*\s)?\\1(\s[a-bA-Z0-9\s]*)?[\"']", $temp);
                    $temp = preg_replace("/\#([a-zA-Z0-9_\-]+)/isx", "[^<>]*\bid=[\"']\\1[\"']", $temp);
                    $temp = preg_replace("/(?<!'|\"|\=|\:|\]|\-|\?|\>|\<|\\\|\*)\b([a-zA-Z0-9_]+)\b(?!'|\"|\=|\[|\-|\?|\>|\<|\\\|\*)/isx", "<\\1", $temp);
                    $temp = preg_replace_callback("/\:([a-zA-Z0-9_]+)/isx", "chec", $temp);
                    $temp = str_replace("\"", "\\\"", $temp);
                    $temp = str_replace("/", "\/", $temp);
                    $is = preg_match("/" . $temp . "/Uisx", $minnr);
                    //|| preg_match("/(\*|html|body)(?!\.|>)/Uisx", $aa[$j]) || $aa[$j] == "<body" || $aa[$j] == "<ul" || $aa[$j] == "<ol" || $aa[$j] == "<li"
                    if ($aa[$j] != "" && $is) {
                        $has = addhas($has, $CSS[$i]);
                        array_splice($CSS, $i, 1);
                        break;
                    }
                }
            }
        }
        return $has;
    }

    function addhas($has, $one)
    {
        $index = indexs($has, $one->xp);
        if ($index >= 0) {
            $has[$index]->style = addStyle($has[$index]->style, $one->style);
        } else {
            $has[] = $one;
        }
        return $has;
    }

    function tou($arr)
    {
        $newarr = array();
        for ($i = 0; $i < count($arr); $i++) {
            $nn = preg_split("/\:/", $arr[$i]);
            if ($nn[0] != "") {
                $newarr[] = $nn[0];
            }
        }
        return $newarr;
    }

    function indexs($arr, $str)
    {
        for ($i = 0; $i < count($arr); $i++) {
            if ($arr[$i]->xp == $str) {
                return $i;
            }
        }
        return -1;
    }

    function che2($em)
    {
        $em[1] = str_replace(">", "&gt;", $em[1]);
        return ">" . $em[1] . "<";
    }

    function che3($em)
    {
        $em[1] = str_replace("<", "&lt;", $em[1]);
        $s = ">" . $em[1] . "<";
        return $s;
    }

    function che4($em)
    {
        $em[3] = preg_replace("/\>/", "&gt;", $em[3]);
        $em[3] = preg_replace("/\</", "&lt;", $em[3]);
        return $em[1] . $em[3] . $em[5];
    }

    function addStyle($a, $b)
    {
        $new = array();
        $a = extractsa($a);
        $b = extractsa($b);
        $c = array_merge($a, $b);
        $s = "";
        foreach ($c as $k => $v) {
            $s .= "$k:$v;";
        }
        return $s;
    }

    function extractsa($a)
    {
        $new = array();
        $nn = explode(";", trim($a));
        for ($i = 0; $i < count($nn); $i++) {
            $nn2 = preg_split("/\:(?!\/)/", trim($nn[$i]));
            if (trim($nn2[0]) != "" && trim($nn2[1]) != "") $new[trim($nn2[0])] = trim($nn2[1]);
        }
        return $new;
    }

    function minnr()
    {
        global $ciyao;
        $nr = preg_replace("/^.*<body[^<>]*>|<\/body[^<>]*>.*$/Uisx", "", $_REQUEST['nr']);
        $allnr = preg_replace("/^.*<body[^<>]*>|<\/body[^<>]*>.*$/Uisx", "", $_REQUEST['source']);
        $allnr = str_replace(trim($nr), "[main]", $allnr);
        $allnr = preg_replace("/<script[^<>]*>.*<\/script>/Uisx", "", $allnr);
        $allnr = preg_replace("/<style[^<>]*>.*<\/style>/Uisx", "", $allnr);
        $allnr = preg_replace("/<\!\-\-(.*)\-\->|<(img|input|br)\b[^<>]*>/Uisx", "", $allnr);
        $allnr = preg_replace("/(?:\s+|\")([^<>\s]+(?<!class|id|style)=)\"[^<>]+(?:\"|(>))/Uisx", " \\2", $allnr);
        $allnr = preg_replace_callback("/>([^<]+)</Uisx", "che2", $allnr);
        $allnr = preg_replace_callback("/>(?>[^>]+(?!\>))</isx", "che3", $allnr);
        $allnr = preg_replace("/(<(?!a)[^<>]*>[^<>]*)(<\/a>)/Uisx", "\\1", $allnr);
        $allnr = preg_replace("/<([^a-zA-Z]+)>/Uisx", "&lt;\\1&gt;", $allnr);
        $allnr = preg_replace("/<([^<>]*[\x{4e00}-\x{9fa5}][^<>]*)>/u", "&lt;\\1&gt;", $allnr);
        $allnr = preg_replace("/<([a-z0-9]+)\b[^<>]*\/>/", "", $allnr);

        $i = 0;
        preg_match("/<([a-z0-9]+)\b[^<>]*>(?:(?<!\[main\])[^<>])*(?<!\[main\])<\/\\1>/Uisx", $allnr, $nn);
        do {
            $allnr = str_replace($nn[0], "", $allnr);
            $i++;
            if ($i > 10000) break;
        } while (preg_match("/<([a-z0-9]+)\b[^<>]*>(?:(?<!\[main\])[^<>])*(?<!\[main\])<\/\\1>/Uisx", $allnr, $nn));
        $allnr = trim($allnr);
        if (!preg_match("/^[^<>]*\[main\]/", $allnr)) {
            $i = 0;
            do {
                $allnr = str_replace($nn[0], "", $allnr);
                $allnr = preg_replace_callback("/>([^<]+)</Uisx", "che2", $allnr);
                $allnr = preg_replace_callback("/>((?:[^>](?!>))+)</Uisx", "che3", $allnr);
                for ($j = 0; $j < count($ciyao); $j++) {
                    $a = $ciyao[$j];
                    $allnr = preg_replace("/(<(?!" . $a . ")[^<>]*>[^<>]*)<\/" . $a . ">/Uisx", "\\1", $allnr);
                    $allnr = preg_replace("/<" . $a . "[^<>]*>([^<>]*<\/(?!" . $a . ")\b[^<>]*>)/Uisx", "\\1", $allnr);
                }
                $i++;
            } while (preg_match("/<([a-z0-9]+)\b[^<>]*>(?:(?<!\[main\])[^<>])*(?<!\[main\])<\/\\1>/Uisx", $allnr, $nn));
        }
        $allnr = str_replace("[main]", $nr, trim($allnr));
        $allnr = beautiful($allnr);
        return $allnr;
    }

    function cssStr($css)
    {
        $s = "";
        for ($i = 0; $i < count($css); $i++) {
            $s .= $css[$i]->xp . "{" . $css[$i]->style . "}\r\n";
        }
        return $s;
    }

    function createcssarr($allclass)
    {
        preg_match_all("/^(.*)$/m", $allclass, $nn);
        $cssarr = array();
        for ($i = 0; $i < count($nn[1]); $i++) {
            if (trim($nn[1][$i]) == "") {
                continue;
            }
            preg_match("/^(.*)\{(.*)\}/Uisx", $nn[1][$i], $nn2);
            $xpath = xpath($nn2[1]);
            $oo = explode(",", $xpath);
            for ($j = 0; $j < count($oo); $j++) {
                $name = trim($oo[$j]);
                $style = str_replace("\"", "\\\"", trim($nn2[2]));
                $cssarr[] = "{\"xp\":\"{$name}\",\"style\":\"{$style}\"}";
            }
        }
        for ($i = 0; $i < count($cssarr); $i++) {
            $cssarr[$i] = json_decode($cssarr[$i]);
        }
        return $cssarr;
    }
}

$ciyao = array("a", "link", "p", "br", "meta", "dd", "nav");
$url = "";
$cookie = "";
$referer = "http://nn.ilaoyou.com/index.php?XDEBUG_SESSION_START=20170327164657&app=seller_order";
$_REQUEST['url'] = ($_REQUEST['url'] == "") ? $url : $_REQUEST['url'];
$_REQUEST['cookie'] = ($_REQUEST['cookie'] == "") ? $cookie : $_REQUEST['cookie'];
$pq=new Pq();

$has = array();
if ($_REQUEST['B1']) {
    $q = new myzhuaqu();
    $_REQUEST['url']=urldecode($_REQUEST['url']);
    if (!preg_match("/^http/i", $_REQUEST['url'])) {
        $_REQUEST['url'] = "http://" . $_REQUEST['url'];
    }
    if (preg_match("/https?:\/\/[^\/]*$/Uisx", $_REQUEST['url'])) {
        $_REQUEST['url'] = $_REQUEST['url'] . "/";
    }
    $source = $q->curl($_REQUEST['url'], "", $_REQUEST['cookie'], $referer);
    $source = dquanurl($source, $_REQUEST['url']);
    preg_match_all("/<link[^<>]*href=[\"']([^<>]*\.css[^<>]*)[\"'\s$]/Uisx", $source, $nn);
    $allclass = "";
    for ($i = 0; $i < count($nn[1]); $i++) {
        $cssurl = $nn[1][$i];
        $nr = $q->curl(quanurl($cssurl, $_REQUEST['url']));
        $nr = clcss($nr, $cssurl);
        $allclass .= $nr;
    }
    preg_match_all("/<style[^<>]*>(.*)<\/style>/Uisx", $source, $nn);
    for ($i = 0; $i < count($nn[1]); $i++) {
        $allclass .= clcss($nn[1][$i], $cssurl);
    }
    $_SESSION['cssarr'] =createcssarr($allclass);
    echo $source;
    exit(0);
}


if ($_REQUEST['savebd']){
    $q = new myzhuaqu();
    if (!preg_match("/^http/i", $_REQUEST['url'])) {
        $_REQUEST['url'] = "http://" . $_REQUEST['url'];
    }
    if (preg_match("/https?:\/\/[^\/]*$/Uisx", $_REQUEST['url'])) {
        $_REQUEST['url'] = $_REQUEST['url'] . "/";
    }
    $source = $q->curl($_REQUEST['url'], "", $_REQUEST['cookie'], $referer);
    $source = dquanurl($source, $_REQUEST['url']);
    preg_match_all("/<link[^<>]*href=[\"']([^<>]*\.css[^<>]*)[\"'\s$]/Uisx", $source, $nn);
    $allclass = "";
    for ($i = 0; $i < count($nn[1]); $i++) {
        $cssurl = $nn[1][$i];
        $url=quanurl($cssurl, $_REQUEST['url']);
        $nr = $q->urlsavebd($url);

        preg_match_all("/url\(([^<>]*\.(jpg|jpeg|gif|png)[^<>]*)[\)\s$]/Uisx", $nr, $nn22);
        for ($j = 0; $j < count($nn22[1]); $j++) {
            $cssurl = preg_replace("/\"|'/","",$nn22[1][$j]);
            $url=quanurl($cssurl, $url);
            $nr = $q->urlsavebd($url);
        }
    }

    preg_match_all("/<script[^<>]*src=[\"']([^<>]*\.js[^<>]*)[\"'\s$]/Uisx", $source, $nn);
    for ($i = 0; $i < count($nn[1]); $i++) {
        $cssurl = $nn[1][$i];
        $url=quanurl($cssurl, $_REQUEST['url']);
        $nr = $q->urlsavebd($url);
    }

    preg_match_all("/<img[^<>]*src=[\"']([^<>]*\.(jpg|jpeg|gif|png)[^<>]*)[\"'\s$]/Uisx", $source, $nn);
    for ($i = 0; $i < count($nn[1]); $i++) {
        $cssurl = $nn[1][$i];
        $url=quanurl($cssurl, $_REQUEST['url']);
        $nr = $q->urlsavebd($url);
    }

}

if ($_REQUEST['act'] == "fx") {
    $nnhas = array();
    $main=$_REQUEST['main'];
    $main=($mail=="undefined"||$mail=="")?"main":$main;
    $_REQUEST['nr'] = delr(urldecode($_REQUEST['nr']));
    $_REQUEST['source'] = delr(urldecode($_REQUEST['source']));
    if(!preg_match("/<\!DOCTYPE\s+html>/Uisx",$_REQUEST['source'])){
        $_REQUEST['source'] ="<!DOCTYPE html>\r\n".$_REQUEST['source'];
    }
    if(!preg_match("/id=\"main\"/Uisx",$_REQUEST['source'])&&preg_match("/<style>(.*)<\/style>(.*)$/Uisx",$_REQUEST['source'],$nn)){
        $cssarr_new =createcssarr($nn[1]);
        $_REQUEST['source']=preg_replace("/(<\/style>\s*<[^<>]*)>/Uisx","\\1 id=\"main\">",$_REQUEST['source']);
    }

    $nr = $_REQUEST['nr'];
    $CSS = (!empty($cssarr_new))?$cssarr_new:$_SESSION['cssarr'];
    $cssStr=cssStr($CSS);

    $o=$pq->newpq($_REQUEST['source']);
    $o=pq("#{$main}");
    $minnr=$pq->qianhou("#{$main}");


    $has=findCss($o);
    if($minnr=="") exit;

    $css = "";
    for ($i = 0; $i < count($has); $i++) {
        if(substr($has[$i],0,1)!="{") $css .=$has[$i]."\r\n";
    }

    //整理$css
    preg_match_all("/^([^\r\n]+)\{([^\r\n]+)\}/Uimx",$css,$nn);
    for($i=0;$i<count($nn[1]);$i++){
        $yuanarr=array();
        for($j=$i+1;$j<count($nn[1]);$j++){
            if($nn[1][$j]==$nn[1][$i]){
                $yuanarr=(empty($yuanarr))?explode(";",$nn[2][$i]):$yuanarr;
                $newarr=explode(";",$nn[2][$j]);
                $yuanarr_tou=tou($yuanarr);
                $newarr_tou=tou($newarr);
                for($n=0;$n<count($newarr);$n++){
                    if(!in_array($newarr_tou[$n],$yuanarr_tou)){
                        $yuanarr[]=$newarr[$n];
                    }else{
                        for($m=0;$m<count($yuanarr);$m++){
                            $nnff=explode(":",$yuanarr[$m]);
                            if($nnff[0]==$newarr_tou[$n]){
                                unset($yuanarr[$m]);
                            }
                        }
                        $yuanarr[]=$newarr[$n];
                    }
                }
                $css=str_replace($nn[0][$j],"",$css);
            }
        }
        if(!empty($yuanarr))$css=str_replace($nn[0][$i],$nn[1][$i]."{".join(";",$yuanarr)."}",$css);
    }
    $css=preg_replace("/\n\s*\r/","",$css);
    $minnr=preg_replace("/\s+style=\"background-color\:\s+rgb\(238,\s+238,\s+238\);\"/Uisx","",$minnr);
    $minnr=preg_replace("/\s+id=\"main\"/Uisx","",$minnr);
    $minnr=preg_replace("/\s+?selected/isx","",$minnr);
    $minnr=preg_replace("/\s+tyle=\"\"/isx","",$minnr);
    $data['body'] = "<style>\r\n" . $css . "\r\n</style>\r\n" . $minnr;
    //$data['css'] = $css;
    $header = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<meta http-equiv="X-UA-Compatible" content="IE=7" /> 
<title></title> 
</head><body>';
    $footer = "</body><html>";
    //fopenw("testpage.php",$header.$data['body'].$footer);
    echo json_encode($data);
    exit;
}